package com.xy.config;

import com.xy.pojo.User;
import com.xy.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *  自定义的UserRealm
 */
public class UserRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了===>授权AuthorizationInfo");
        //授权信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

       //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了===>认证AuthenticationInfo");
        //模拟数据库的用户名和密码
//        String name = "root";
//        String password = "123456";

        //转换成Shiro需要的对象
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        //查询数据库
        User user = userService.queryUser(userToken.getUsername());

        //用户名认证
        if (user==null){
            return null;//返回 null 就是抛出异常UnknownAccountException
        }
        //密码认证，shiro做,不需要我们做
        //参数1：传递个授权的当前用户，参数2：当前用户密码，密码认证shiro会做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
